#!/bin/bash
# DeepGP Streamlit 应用启动脚本

echo "=========================================="
echo "  DeepGP - 糖肽谱图与保留时间预测平台"
echo "=========================================="
echo ""

# 获取脚本所在目录和项目根目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
cd "$PROJECT_ROOT"

# 环境名称
ENV_NAME="deepgp"

# 检查 conda 是否可用
if command -v conda &> /dev/null; then
    echo "✓ 检测到 Conda"
    
    # 检查环境是否存在
    if conda env list | grep -q "^${ENV_NAME} "; then
        echo "✓ 找到 ${ENV_NAME} 环境"
    else
        echo "⚠️  ${ENV_NAME} 环境不存在"
        echo "请先运行安装脚本:"
        echo "  ./setup_env_china.sh (中国国内用户，推荐)"
        echo "  或 ./setup_env.sh (国际用户)"
        exit 1
    fi
    
    # 激活环境
    echo "正在激活 ${ENV_NAME} 环境..."
    source "$(conda info --base)/etc/profile.d/conda.sh"
    conda activate ${ENV_NAME}
    
    if [ $? -ne 0 ]; then
        echo "❌ 激活环境失败"
        exit 1
    fi
    
    echo "✓ 环境已激活: ${ENV_NAME}"
else
    echo "⚠️  未检测到 Conda，使用系统 Python"
fi

# ⚠️ 关键：每次启动时检查并修复 numpy 和 pandas 版本
echo ""
echo "=========================================="
echo "  检查关键依赖版本"
echo "=========================================="

python << 'EOF'
import sys

def check_and_fix_versions():
    issues = []
    
    # 检查 numpy
    try:
        import numpy as np
        numpy_version = np.__version__
        major = int(numpy_version.split('.')[0])
        if major >= 2:
            issues.append(('numpy', numpy_version, '<2.0'))
            print(f"⚠️  NumPy 版本过高: {numpy_version} (需要 <2.0)")
    except:
        issues.append(('numpy', 'None', '<2.0'))
        print(f"❌ NumPy 未安装")
    
    # 检查 pandas
    try:
        import pandas as pd
        pandas_version = pd.__version__
        major = int(pandas_version.split('.')[0])
        if major >= 2:
            issues.append(('pandas', pandas_version, '<2.0'))
            print(f"⚠️  Pandas 版本过高: {pandas_version} (需要 <2.0)")
    except:
        issues.append(('pandas', 'None', '<2.0'))
        print(f"❌ Pandas 未安装")
    
    if not issues:
        print("✓ NumPy 和 Pandas 版本正确")
        return True
    
    # 自动修复
    print("\n🔧 自动修复中...")
    import subprocess
    try:
        cmd = ['pip', 'install', 'numpy<2.0', 'pandas<2.0', '-i', 'https://pypi.tuna.tsinghua.edu.cn/simple', '--force-reinstall', '-q']
        subprocess.run(cmd, check=True, capture_output=True)
        print("✓ 版本修复成功")
        return True
    except:
        print("❌ 自动修复失败，请手动执行:")
        print("  pip install 'numpy<2.0' 'pandas<2.0' --force-reinstall")
        return False

if not check_and_fix_versions():
    sys.exit(1)
EOF

if [ $? -ne 0 ]; then
    echo ""
    echo "❌ 依赖版本检查失败"
    echo "请运行: ./install.sh (选择选项 3 快速修复)"
    exit 1
fi

# 配置 HuggingFace 镜像（国内用户）
export HF_ENDPOINT=https://hf-mirror.com
echo "✓ 已配置 HuggingFace 镜像: ${HF_ENDPOINT}"

# 快速检查关键依赖
echo ""
echo "快速检查关键依赖..."

python << 'EOF'
missing = []
try:
    import torch
    print(f"✓ PyTorch {torch.__version__}")
except:
    missing.append("PyTorch")
    print("❌ PyTorch 未安装")

try:
    import dgl
    print(f"✓ DGL {dgl.__version__}")
except:
    missing.append("DGL")
    print("❌ DGL 未安装")

try:
    import streamlit
    print(f"✓ Streamlit {streamlit.__version__}")
except:
    missing.append("Streamlit")
    print("❌ Streamlit 未安装")

if missing:
    print(f"\n❌ 缺失依赖: {', '.join(missing)}")
    print("\n请运行安装脚本:")
    print("  ./install.sh")
    import sys
    sys.exit(1)
EOF

if [ $? -ne 0 ]; then
    echo ""
    echo "请先安装依赖后再启动"
    exit 1
fi

echo "✓ 所有依赖已安装"
echo ""

# 检查端口是否被占用
PORT=8501
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "⚠️  端口 $PORT 已被占用"
    echo "尝试使用端口 8502..."
    PORT=8502
fi

echo "🚀 启动 DeepGP Web 应用..."
echo ""
echo "访问地址: http://localhost:$PORT"
echo "按 Ctrl+C 停止应用"
echo ""
if command -v conda &> /dev/null; then
    echo "当前环境: ${ENV_NAME}"
fi
echo "=========================================="
echo ""

# 启动应用
streamlit run streamlit_app/app.py --server.port $PORT

